var $ = require('jquery');
/**
 * dropDownButton jquery plugin that can simple simulator pop menu
 * and it always be used to website topheader pop dropdown menu Interactive experience.
 * dependency: jquery.1.4.2 +
 * create by terence tian
 * datatime:2012-11-13
 * issue: IE7 transparent bug: mouseleave/mouseover is triggering in IE7 while the cursor is still over the element
 * quick fix: we must set the background(the element that bind mouseleave/mouseout event) as "white" or having 1x1.gif as background.
 */

// The default configurations.
var defaults = {
    activeClass: "hover",
    timeout: 60,
    direction: "right"
};

/**
 * DropDownMenu class. eg. $elem=ddButton Object,options={list:$ddButtonList,topNav:$topNav}
 * @param {array} $elems  [jquery object]
 * @param {array} options [jquery selector list matched elems]
 */

var DropdownButton = function ($elem, options) {
    var cfg = $.extend({}, defaults, options);
    this.activeClass = cfg.activeClass;
    this.timeout = cfg.timeout;
    // Top Nav Selector
    this.$topNav = cfg.topNav;
    this.$ddButton = $elem;
    // Pop List Selector
    this.$ddList = cfg.list;
    // indicate the ddList container left justify of ddButton. 
    this.direction = "right";
    // give offset value used to adjust the positon of ddList when direction='left'. eg. 10 | -10
    this.offset = cfg.offset;
    // the callback function should be invoked while the dropdownbutton actived.
    this.callback = cfg.callback;

    return this;
};
DropdownButton.prototype = {
    init: function () {
        // init timer of current Dropdownbutton instance.
        this.timer = 0;
        // active
        this.active();

        this.ddButtonWidth = this.$ddButton.outerWidth();
        this.ddListWidth = this.$ddList.outerWidth();
        if (this.ddButtonWidth > this.ddListWidth) {
            this.ddListWidth = this.ddButtonWidth;
        }
    },
    active: function () {
        var self = this;
        self.$ddButton.bind("mouseenter", function () {
            var $this = $(this);
            if (self.timer) self.timer = clearTimeout(self.timer);
            // Add mouseenter active class on ddbutton.
            $this.addClass(self.activeClass);
            self.$ddList.css({
                display: 'block',
                top: ($this.offset().top - self.$topNav.offset().top + $this.height()) + self.offset.y
            });

            // Diff with of ddButtom and ddList 
            var topNavOffsetLeft = self.$topNav.offset().left;
            // Make sure that the with of $ddList > with of $ddbutton 
            self.$ddList.css({
                width: self.ddListWidth
            });
            // make sure that the right has enought space to show ddList. otherwise set direction to left.
            var _left = self.$topNav.outerWidth() + topNavOffsetLeft;
            if ($this.offset().left + self.ddListWidth > _left) {
                self.direction = "left";
            }
            if (self.direction == "right") {
                self.$ddList.addClass("d-right").css({
                    left: $this.offset().left - topNavOffsetLeft + self.offset.right_x
                });
            } else {
                self.$ddList.addClass("d-left").css({
                    left: $this.offset().left - topNavOffsetLeft + self.offset.left_x - self.ddListWidth + self.ddButtonWidth
                });
            }
            // invoke callback function.
            if ($.isFunction(self.callback)) self.callback(self.$ddList);

        }).bind("mouseleave", function () {
            self.timer = setTimeout(function () {
                self.$ddButton.removeClass(self.activeClass);
                self.$ddList.css({
                    display: 'none'
                });
            }, self.timeout)
        });
        // bind mouseenter,mouseleave event with $ddlist.
        self.$ddList.bind("mouseenter", function () {
            if (self.timer) self.timer = clearTimeout(self.timer);
        }).bind("mouseleave", function () {
            self.timer = setTimeout(function () {
                self.$ddButton.removeClass(self.activeClass);
                self.$ddList.css({
                    display: 'none'
                });
            }, self.timeout);
        });
    }
};
/**
 * dom sample:
 * 
 * <div class="popup-dropdown-list-wrapper">
    <div class="group popup-list">
        <div class="title">
            CPU Type
            <span class="arrow"></span>
        </div>
        <div class="group-items">
                <div class="item">
                    <a href="http://localhost:700/desktops?specs=5">AMD</a>
                </div>
                <div class="item">
                    <a href="http://localhost:700/desktops?specs=6">Intel</a>
                </div>
        </div>
    </div>
    <div class="group popup-list">
        <div class="title">
            Memory
            <span class="arrow"></span>
        </div>
        <div class="group-items">
                <div class="item">
                    <a href="http://localhost:700/desktops?specs=7">1 GB</a>
                </div>
        </div>
    </div>
    <div class="group popup-list">
        <div class="title">
            Hardrive
            <span class="arrow"></span>
        </div>
        <div class="group-items">
                <div class="item">
                    <a href="http://localhost:700/desktops?specs=11">160 GB</a>
                </div>
                <div class="item">
                    <a href="http://localhost:700/desktops?specs=10">250 GB</a>
                </div>
                <div class="item">
                    <a href="http://localhost:700/desktops?specs=9">320 GB</a>
                </div>
        </div>
    </div>
</div>
 * .dropDownButton(".popup-list", {topNav:'.popup-dropdown-list-wrapper', btnSelector:'.title', listSelector:'.group-items', activeClass: "hover",timeout: '60'});
 * 
 * Note: .title, .group-items must be nasted in .popup-list
 * the topNav is used to calculate the relative position for each position of listSelector.
 */
exports.dropDownButton = function (selector, options) {
    // make sure the offset exist
    options.offset = options.offset || {
        y: 0,
        left_x: 0,//left direction 
        right_x: 0// right direction 
    };
    // the root node for all ddList related to .
    var $topNav = $(options.topNav);

    $(selector).each(function (index, item) {
        var $this = $(item);
        var $thisList = $this.find(options.listSelector);
        var $drpButton = $this.find(options.btnSelector);

        var newOpts = $.extend(options, {
            list: $thisList,
            topNav: $topNav,
            activeClass: "hover",
            timeout: '60'
        });

        new DropdownButton($drpButton, newOpts).init();
    });
};